#include "stdinc.h"
#include <CEGUI.h>
#include "Main/Logger.h"

#include "GUI/Console.h"

using namespace GUI;



Console::Console(CEGUI::Window *parentSheet)
		: mHistorySize(100)
{
	
	mConsole = CEGUI::WindowManager::getSingleton().loadWindowLayout("Console.layout");

	parentSheet->addChildWindow(mConsole);
	mCommandLine = (CEGUI::Editbox*)CEGUI::WindowManager::getSingleton().getWindow("/Console/CommandLine");
	mConsoleLog = (CEGUI::Listbox*) CEGUI::WindowManager::getSingleton().getWindow("/Console/ConsoleLog");

	mConsole->hide();
	Main::Logger::getSingleton().registerListener(this,true);

}


Console::~Console()
{
  
}


void Console::receiveLogMessage(const std::string message,time_t timestamp,const std::string source) 
{
	char timebuf[50];
	_strtime_s(timebuf,50);
	std::string msg = "[" +source+" @" + timebuf +"]:" + message;


	CEGUI::ListboxTextItem* msgItem;
	if(mConsoleLog->getItemCount() == mHistorySize)
	{
		msgItem = static_cast<CEGUI::ListboxTextItem*>(mConsoleLog->getListboxItemFromIndex(0));
		msgItem->setAutoDeleted(false);
		mConsoleLog->removeItem(msgItem);
		msgItem->setAutoDeleted(true);
		msgItem->setText(msg);
	}
	else
	{
		// Create a new listbox item
		msgItem = new CEGUI::ListboxTextItem(msg);
	}
	mConsoleLog->addItem(msgItem);
	mConsoleLog->ensureItemIsVisible(mConsoleLog->getItemCount());
}


void Console::hide() 
{
	mConsole->hide();
}

void Console::show() 
{
	mConsole->show();
}

void Console::toggle() 
{
	if (mConsole->isVisible(true)) 
		mConsole->hide();
	else
		mConsole->show();
}

